package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.jobPosting.JobPostingAddRequest;
import com.YHVision.qiuzhike.model.dto.jobPosting.JobPostingEditRequest;
import com.YHVision.qiuzhike.model.dto.jobPosting.JobPostingQueryRequest;
import com.YHVision.qiuzhike.model.dto.jobPosting.JobPostingUpdateRequest;
import com.YHVision.qiuzhike.model.entity.JobPosting;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.JobPostingVO;
import com.YHVision.qiuzhike.service.JobPostingService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 企业招聘接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/jobPosting")
@Slf4j
public class JobPostingController {

    @Resource
    private JobPostingService jobPostingService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建企业招聘
     *
     * @param jobPostingAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.COMPANY_ROLE)
    public BaseResponse<Long> addJobPosting(@RequestBody JobPostingAddRequest jobPostingAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(jobPostingAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        JobPosting jobPosting = new JobPosting();
        BeanUtils.copyProperties(jobPostingAddRequest, jobPosting);
        // 数据校验
        jobPostingService.validJobPosting(jobPosting, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        jobPosting.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = jobPostingService.save(jobPosting);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newJobPostingId = jobPosting.getId();
        return ResultUtils.success(newJobPostingId);
    }

    /**
     * 删除企业招聘
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.COMPANY_ROLE)
    public BaseResponse<Boolean> deleteJobPosting(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        JobPosting oldJobPosting = jobPostingService.getById(id);
        ThrowUtils.throwIf(oldJobPosting == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldJobPosting.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = jobPostingService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新企业招聘（仅管理员可用）
     *
     * @param jobPostingUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.COMPANY_ROLE)
    public BaseResponse<Boolean> updateJobPosting(@RequestBody JobPostingUpdateRequest jobPostingUpdateRequest) {
        if (jobPostingUpdateRequest == null || jobPostingUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        JobPosting jobPosting = new JobPosting();
        BeanUtils.copyProperties(jobPostingUpdateRequest, jobPosting);
        // 数据校验
        jobPostingService.validJobPosting(jobPosting, false);
        // 判断是否存在
        long id = jobPostingUpdateRequest.getId();
        JobPosting oldJobPosting = jobPostingService.getById(id);
        ThrowUtils.throwIf(oldJobPosting == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = jobPostingService.updateById(jobPosting);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取企业招聘（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<JobPostingVO> getJobPostingVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        JobPosting jobPosting = jobPostingService.getById(id);
        ThrowUtils.throwIf(jobPosting == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(jobPostingService.getJobPostingVO(jobPosting, request));
    }

    /**
     * 分页获取企业招聘列表（仅管理员可用）
     *
     * @param jobPostingQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.COMPANY_ROLE)
    public BaseResponse<Page<JobPosting>> listJobPostingByPage(@RequestBody JobPostingQueryRequest jobPostingQueryRequest) {
        long current = jobPostingQueryRequest.getCurrent();
        long size = jobPostingQueryRequest.getPageSize();
        // 查询数据库
        Page<JobPosting> jobPostingPage = jobPostingService.page(new Page<>(current, size),
                jobPostingService.getQueryWrapper(jobPostingQueryRequest));
        return ResultUtils.success(jobPostingPage);
    }

    /**
     * 分页获取企业招聘列表（封装类）
     *
     * @param jobPostingQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<JobPostingVO>> listJobPostingVOByPage(@RequestBody JobPostingQueryRequest jobPostingQueryRequest,
                                                               HttpServletRequest request) {
        long current = jobPostingQueryRequest.getCurrent();
        long size = jobPostingQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<JobPosting> jobPostingPage = jobPostingService.page(new Page<>(current, size),
                jobPostingService.getQueryWrapper(jobPostingQueryRequest));
        // 获取封装类
        return ResultUtils.success(jobPostingService.getJobPostingVOPage(jobPostingPage, request));
    }

    /**
     * 分页获取当前登录用户创建的企业招聘列表
     *
     * @param jobPostingQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<JobPostingVO>> listMyJobPostingVOByPage(@RequestBody JobPostingQueryRequest jobPostingQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(jobPostingQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        jobPostingQueryRequest.setUserId(loginUser.getId());
        long current = jobPostingQueryRequest.getCurrent();
        long size = jobPostingQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<JobPosting> jobPostingPage = jobPostingService.page(new Page<>(current, size),
                jobPostingService.getQueryWrapper(jobPostingQueryRequest));
        // 获取封装类
        return ResultUtils.success(jobPostingService.getJobPostingVOPage(jobPostingPage, request));
    }

    /**
     * 编辑企业招聘（给用户使用）
     *
     * @param jobPostingEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.COMPANY_ROLE)
    public BaseResponse<Boolean> editJobPosting(@RequestBody JobPostingEditRequest jobPostingEditRequest, HttpServletRequest request) {
        if (jobPostingEditRequest == null || jobPostingEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        JobPosting jobPosting = new JobPosting();
        BeanUtils.copyProperties(jobPostingEditRequest, jobPosting);
        // 数据校验
        jobPostingService.validJobPosting(jobPosting, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = jobPostingEditRequest.getId();
        JobPosting oldJobPosting = jobPostingService.getById(id);
        ThrowUtils.throwIf(oldJobPosting == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldJobPosting.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = jobPostingService.updateById(jobPosting);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
